package com.kawins.util.file;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author rankai
 *         createTime 2017-10-2017/10/31 13:45
 */
public class FileUtil {

    private static final String FILE_WIN_SEPARATOR = "\\";

    private static final String FILE_LINUX_SEPARATOR = "/";

    /**
     * @param map
     */
    public static void upload(Map<String, MultipartFile> map) {
        for (Map.Entry<String, MultipartFile> entry : map.entrySet()) {
            upload(entry.getKey(), entry.getValue());
        }
    }

    /**
     * @param path
     * @param multipartFile
     */
    public static void upload(String path, MultipartFile multipartFile) {
        if (path == null || multipartFile == null) {
            return;
        }
        File file = new File(buildOsPath(path));
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 写入文件,末尾自动添加\r\n
     *
     * @param path
     * @param str
     */
    public static void write(String path, String str) {
        try {
            File file = new File(buildOsPath(path));
            if (!file.exists())
                file.createNewFile();
            FileOutputStream out = new FileOutputStream(file); //true表示追加
            StringBuffer sb = new StringBuffer();
            sb.append(str + "\r\n");
            out.write(sb.toString().getBytes("utf-8"));
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 整个文件以string放回，添加\r\n换行
     *
     * @param path
     * @return
     */
    public static String readToString(String path) {
        StringBuffer sb = new StringBuffer();
        String tempStr;
        BufferedReader br = null;
        try {
            File file = new File(buildOsPath(path));
            if (!file.exists())
                throw new FileNotFoundException();
            FileInputStream fis = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
            while ((tempStr = br.readLine()) != null) {
                sb.append(tempStr + "\r\n");
            }
        } catch (IOException ex) {
            ex.getStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * 按行读取文件，以list<String>的形式返回
     *
     * @param path
     * @return
     */
    public static List<String> readToList(String path) {
        List<String> lines = new ArrayList<>();
        String tempStr;
        BufferedReader br = null;
        try {
            File file = new File(buildOsPath(path));
            if (!file.exists()) {
                throw new FileNotFoundException();
            }
            FileInputStream fis = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
            while ((tempStr = br.readLine()) != null) {
                lines.add(tempStr.toString());
            }
        } catch (IOException ex) {
            System.out.println(ex.getStackTrace());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return lines;
    }

    /**
     * 创建目录
     *
     * @param dirPath
     */
    public static void mkDir(String dirPath) {
        File myFolderPath = new File(buildOsPath(dirPath));
        try {
            if (!myFolderPath.exists()) {
                myFolderPath.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param filePath
     */
    public static void delAllFile(String filePath) {
        try {
            File file = new File(buildOsPath(filePath));
            if (!file.exists()) {
                return;
            }
            if (file.isFile()) {
                file.delete();
            } else {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    String root = files[i].getAbsolutePath();//得到子文件或文件夹的绝对路径
                    delAllFile(root);
                }
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 得到一个文件夹下所有文件
     */
    public static List<String> getAllFile(String foldPath) {
        List<String> filePaths = new ArrayList<>();
        LinkedList<String> folderList = new LinkedList<>();
        folderList.add(buildOsPath(foldPath));
        while (folderList.size() > 0) {
            File file = new File(folderList.peekLast());
            folderList.removeLast();
            File[] files = file.listFiles();
            ArrayList<File> fileList = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    folderList.add(files[i].getPath());
                } else {
                    fileList.add(files[i]);
                }
            }
            for (File f : fileList) {
                filePaths.add(f.getAbsoluteFile().getPath());
            }
        }
        return filePaths;
    }

    /**
     * @param filePath
     * @return
     */
    public static byte[] file2Byte(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(buildOsPath(filePath));
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * @return
     */
    public static String getSeparator() {
        return File.separator;
    }

    /**
     * @param path
     * @return
     */
    public static String buildOsPath(String path) {
        String replace = path.replace(FILE_WIN_SEPARATOR, getSeparator());
        return replace.replace(FILE_LINUX_SEPARATOR, getSeparator());
    }

    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     */
    public static String getExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}
